from whiff import resolver
from whiff import whiffenv
from whiff.rdjson import jsonParse
from whiff.middleware import callTemplate

def erdDelete(env, start_response):
    env = resolver.process_cgi(env, parse_cgi=True)
    name = whiffenv.cgiGet(env, "name")
    attributes = whiffenv.cgiGet(env, "attributes", "")
    keys = whiffenv.cgiGet(env, "keys")
    rule = whiffenv.cgiGet(env, "Rule")
    x = whiffenv.cgiGet(env, "x")
    y = whiffenv.cgiGet(env, "y")
    #pr "(name, x, y, keys, attributes, rule)", (name, x, y, keys, attributes, rule)
    #x = int(x)
    #y = int(y)
    (x,y) = snapToGrid(x,y)
    rule = resolver.unquote(rule)
    name = name.strip()
    attributes = attributes.split()
    keys = keys.split()
    (flag, rulevalue, cursor) = jsonParse.parseValue(rule)
    if not flag:
        raise ValueError, "failed to parse rule "+repr(rule)
    if not name:
        raise ValueError, "no name found"
    #start_response('200 OK', [('Content-Type', 'application/javascript')])
    #yield "alert('trying to delete element %s');" % name
    #yield "alert('rule is %s');" % rule.replace("\n", " ")
    # remove all mentions of element
    newrule = list(rulevalue)
    newrule.append( ["table", name, keys, attributes, x, y ] )
    env = env.copy()
    newrulestr = jsonParse.format(newrule)
    #pr "new rule is"
    #pr newrulestr
    resolver.override_cgi_require(env, "Rule", newrulestr)
    # deliver the javascript
    #pr "NOW CALLING SCHEMATEST"
    app = callTemplate.callTemplate("schemaTest.js")
    return app(env, start_response)

def snapToGrid(x,y):
    x = int(x)
    y = int(y)
    x = int(x/10)*10
    y = int(y/10)*10
    return (x,y)

__wsgi__ = erdDelete
